#ifndef THREAD_WORK_H
#define THREAD_WORK_H

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

//http://www.wuzesheng.com/?p=1668
#include "getHtml.h"
#include "common.h"

 queue<UrlPath*>  m_qUrlPath;

boost::thread_specific_ptr<queue<UrlPath*> > pptr;

boost::condition_variable_any cond;

boost::recursive_mutex io_mutex;  
class printer
{
public:
    printer(boost::asio::io_service& io,int n)
        : strand_(io),
        timer1_(io, boost::posix_time::seconds(1)),
        timer2_(io, boost::posix_time::seconds(1)),
        count_(n)
    {
		//timer2_.async_wait(boost::bind(&printer::enqueue, this));
        timer1_.async_wait(boost::bind(&printer::dequeue, this));
        
    }

    ~printer()
    {
		 boost::recursive_mutex::scoped_lock  lock(io_mutex); 
        std::cout << "Final count is " << count_ << "\n";
    }

    void dequeue()
    {
		boost::recursive_mutex::scoped_lock  lock(io_mutex); 

		cout<<"------------dequeue "<<count_<<endl;
		                        
        while(m_qUrlPath.empty())
        {
            cond.wait(lock);        
        
        }
        {
        if (!m_qUrlPath.empty())
        {
         
	//		  boost::mutex::scoped_lock lock5(io_mutex);
			cout<<"------------pop "<<count_<<endl;
			//m_qUrlPath.front();
   //         m_qUrlPath.pop();


            UrlPath  * url =  m_qUrlPath.front();
            m_qUrlPath.pop();
            getHtml * gh = new getHtml;
            gh->setUrl(url);
            gh->doWork();
            delete gh;
			
	  

        }
		cond.notify_all();
        }
        timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
        timer1_.async_wait(boost::bind(&printer::dequeue, this));        
    }

	void enqueue()
	{
		boost::recursive_mutex::scoped_lock  lock(io_mutex); 
		cout<<"------------enqueue"<<count_<<endl;

		while(m_qUrlPath.size() == 1000)
		{
          cond.wait(lock);        
        
		}
		UrlPath *	m_UrlPath = new UrlPath;
	m_UrlPath->spath = " ss";
	//doRegex("^(http:\/\/)?([^\/]+)");
	m_UrlPath->shost = "fdfd";//doRegex(regexhost,_url);


	m_qUrlPath.push(m_UrlPath);
			cond.notify_all();
		//}
		timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
		timer1_.async_wait(boost::bind(&printer::enqueue, this));    
		
	}

private:
    boost::asio::strand strand_;
    boost::asio::deadline_timer timer1_;
    boost::asio::deadline_timer timer2_;
    int count_;

	  boost::mutex mtx;
};


#endif